﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using NLog;
using KBVault.DAL.Entities;
using KBVault.DAL.Repository;
using System.Web.Script.Serialization;

namespace KBVault.Web.Public
{
    class JsonResponse
    {
        public string FileName { get; set; }
        public bool Result { get; set; }
        public string ErrorMessage { get; set; }
        public Attachment Attachment{ get; set; }
    }
    /// <summary>
    /// Summary description for Upload
    /// </summary>
    public class Upload : IHttpHandler
    {
        private string GetStoragePath()
        {
            return "/Attachments/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString();
        }
        public void ProcessRequest(HttpContext context)
        {
            List<JsonResponse> jResponse = new List<JsonResponse>();
            try
            {
                if (!String.IsNullOrEmpty(context.Request.Form["Hash"]) && context.Request.Files.Count > 0)
                {
                    string hashKey = context.Request.Form["Hash"].ToString();
                    string storagePath = GetStoragePath();
                    string uploadPath = context.Server.MapPath(storagePath);
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);

                    

                    for (int fileIndex = 0; fileIndex < context.Request.Files.Count;fileIndex++ )
                    {
                        HttpPostedFile uploadedFile = context.Request.Files[fileIndex];
                        Attachment a = new Attachment();
                        a.Hash = hashKey;
                        a.HashTime = DateTime.Now;
                        a.FileName = uploadedFile.FileName;
                        a.Path = storagePath;
                        a.Extension = Path.GetExtension(uploadedFile.FileName).Replace(".","");
                        a.ArticleId = -1;
                        AttachmentRepository.Create(ref a);
                        uploadedFile.SaveAs(uploadPath + "/" + a.Id + "." + a.Extension);                        
                        jResponse.Add(new JsonResponse() { FileName = uploadedFile.FileName, Result = true,Attachment = a});
                    }
                }                
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex.Message);
                jResponse.Clear();
                jResponse.Add(new JsonResponse() { ErrorMessage = ex.Message, Result = false });
            }
            
            JavaScriptSerializer jss = new JavaScriptSerializer();
            context.Response.ContentType = "application/json";
            context.Response.Write(jss.Serialize(jResponse));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}